/*
 * Copyright © 2022-now 尛飛俠（Denvie） All rights reserved.
 */

package cn.denvie.springcloud.seata.account.service.impl;

import cn.denvie.springcloud.seata.account.mapper.AccountMapper;
import cn.denvie.springcloud.seata.account.service.AccountService;
import cn.denvie.springcloud.seata.common.model.entity.Account;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Account服务实现类。
 *
 * @author Denvie
 * @date 2022/4/08
 * @since 1.0.0
 */
@Slf4j
@Service
public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> implements AccountService {
    @Override
    public Account getByUserId(String userId) {
        QueryWrapper<Account> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        return super.getOne(wrapper);
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public void debit(String userId, int money) {
        log.info("=============用户账户扣款=================");

        // 检查余额
        checkBalance(userId, money);

        log.info("开始扣减用户【{}】余额", userId);
        int result = getBaseMapper().reduceBalance(userId, money);
        log.info("扣减用户【{}】余额结果：{}", userId, result > 0 ? "成功" : "失败");
    }

    private void checkBalance(String userId, int money) {
        log.info("检查用户【{}】余额", userId);
        Account account = getByUserId(userId);
        if (account == null) {
            throw new RuntimeException("用户【" + userId + "】不存在");
        }
        if (account.getMoney() < money) {
            log.warn("用户【{}】余额不足，当前余额：{}", userId, account.getMoney());
            throw new RuntimeException("用户【" + userId + "】余额不足");
        }
    }
}
